package mobilecontrollers

import (
	"alarmservice/com"
	"alarmservice/model"
	simplejson "github.com/bitly/go-simplejson"
)

type WarningController struct {
	baseController
}

func (c *WarningController) NextPrepare() {
	c.NeedParams = true
}

//根据参数offset，size 参数获取数据，size默认与最大30
func (c *WarningController) ApiList() {
	offset, offsetErr := c.ParamsJson.Get("offset").Int()
	size, sizeErr := c.ParamsJson.Get("size").Int()
	if offsetErr != nil {
		offset = 0
	}

	if sizeErr != nil || size > 30 {
		size = 30
	}

	warnings := make(model.MapWarning)

	followProjects := make(model.SliceFollowProject, 0)
	err := model.Orm.Where("user_id=?", c.Token.Uid).Limit(size, offset).Find(&followProjects)
	if err != nil {
		c.returnJson(com.ApiUnknowFailed(com.ApiErrMsgSystem))
		return
	}

	projectIds := followProjects.GetProjectIds()
	if len(projectIds) == 0 {
		c.returnJson(com.ApiSucc(warnings))
		return
	}

	err = model.Orm.In("project_id", projectIds).OrderBy("create_time desc").Limit(size, offset).Find(&warnings)
	if err != nil {
		c.returnJson(com.ApiUnknowFailed(com.ApiErrMsgSystem))
		return
	}

	projects, err := model.GetProjectFromProjectIdContainer(warnings)
	if err != nil {
		c.returnJson(com.ApiUnknowFailed(com.ApiErrMsgSystem))
		return
	}

	tracings, err := model.GetTracingFromTracingIdContainer(warnings)
	if err != nil {
		c.returnJson(com.ApiUnknowFailed(com.ApiErrMsgSystem))
		return
	}

	json := simplejson.New()
	json.Set("warnings", model.MapIntKeyToStr(warnings))
	json.Set("projects", model.MapIntKeyToStr(projects))
	json.Set("tracings", model.MapIntKeyToStr(tracings))

	c.returnJson(com.ApiSucc(json))
	return
}

//根据warning_id参数获取Warning相关信息,Project，Tracing，创始人等
func (c *WarningController) ApiDetail() {
	warningId, err := c.ParamsJson.Get("warning_id").Int64()

	if err != nil {
		c.returnJson(com.ApiUnknowFailed(com.ApiErrMsgNeedParam))
		return
	}
	warning := &model.Warning{}
	err = model.GetById(warningId, warning)

	if err != nil {
		c.returnJson(com.ApiUnknowFailed(com.ApiErrMsgSystem))
		return
	}

	//获取project
	project := &model.Project{}
	projectErr := model.GetById(warning.ProjectId, project)

	//获取tracing
	tracing := &model.Tracing{}
	tracingErr := model.GetById(warning.TracingId, tracing)

	if projectErr != nil || tracingErr != nil {
		c.returnJson(com.ApiUnknowFailed(com.ApiErrMsgSystem))
		return
	}

	//获取user
	projectUser, err := model.GetAdminUserById(project.UserId)
	if err != nil {
		c.returnJson(com.ApiUnknowFailed(com.ApiErrMsgSystem))
		return
	}

	//XXX 需要检查是否user信息相同

	json := simplejson.New()
	json.Set("warning", warning)
	json.Set("project", project)
	json.Set("tracing", tracing)
	json.Set("project_user", projectUser)

	c.returnJson(com.ApiSucc(json))
	return
}
